<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="位置" prop="position">
        <el-input
          v-model="queryParams.position"
          placeholder="请输入位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属经营户(或场所)" prop="companyName" label-width="150px">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入所属经营户(或场所)"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属场站" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入所属场站"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5" v-if="station_btn">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ledger:equipment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="station_btn">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['ledger:equipment:import']"
        >导入</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" :max-height="tableHeight" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="位置" align="left" prop="position" />
      <el-table-column label="经营户(或场所)" align="left" prop="companyName" />
      <el-table-column label="灭火器数量" align="center" prop="fireExtinguisherNumber" />
      <el-table-column label="消防箱数量" align="center" prop="fireBoxNumber" />
      <el-table-column label="水带数量" align="center" prop="waterBeltNumber" />
      <el-table-column label="枪头数量" align="center" prop="gunHeadNumber" />
      <el-table-column label="所属场站" align="left" prop="stationName" width="300" v-if="!station_btn"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ledger:equipment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ledger:equipment:remove']"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消防设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="位置:" prop="position">
              <el-input v-model="form.position" placeholder="请输入位置" maxlength="30"  show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型:"  prop="checkType">
              <el-radio-group v-model="form.checkType" @change="checkType(form.checkType)">
                <el-radio
                  v-for="dict in dictList"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属经营户(或场所):" prop="companyName">
              <el-input :disabled="check_show"  v-model="form.companyName" :placeholder="check_content" maxlength="30"  show-word-limit :style="'width:'+check_height+';'"/>
              <div @click="selectBussiness()"  class="to-search" :style="'float:right;margin-right:20px;display: '+div_show+''">
                <span class="el-icon-search" ></span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="灭火器数量:" prop="fireExtinguisherNumber">
              <el-input-number v-model="form.fireExtinguisherNumber" style="width: 100%" placeholder="请输入消防器数量" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消防箱数量:" prop="fireBoxNumber">
              <el-input-number v-model="form.fireBoxNumber" style="width: 100%" placeholder="请输入消防箱数量" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="消防箱尺寸:" prop="fireBoxSize">
              <el-input v-model="form.fireBoxSize" placeholder="请输入消防箱尺寸" maxlength="40"  show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="玻璃尺寸:" prop="glassSize">
              <el-input v-model="form.glassSize" placeholder="请输入玻璃尺寸" maxlength="40"  show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="水带数量:" prop="waterBeltNumber">
              <el-input-number v-model="form.waterBeltNumber" style="width: 100%" placeholder="请输入水带数量" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="枪头数量:" prop="gunHeadNumber">
              <el-input-number v-model="form.gunHeadNumber" style="width: 100%" placeholder="请输入枪头数量" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" maxlength="200"  show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传图片:">
              <el-upload
                :multiple="true"
                accept=".jpg, .png, .gif, .bmp, .jpeg"
                :headers="uploadImg.headers"
                :action="uploadImg.url"
                :file-list="form.imgList"
                list-type="picture-card"
                :limit="uploadImg.limit"
                :before-upload="beforeImageUpload"
                :on-exceed="exceedFile"
                :on-success="handlePictureSuccess"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/bmp/jpeg文件，且不超过10M</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <el-dialog title="选择经营户" :visible.sync="openBusiness" width="800px">
      <el-form :model="queryBusinessParams" ref="queryBusinessForm" :inline="true" label-width="68px">
        <el-form-item label="名称" prop="companyName" :width="150">
          <el-input
            v-model="queryBusinessParams.companyName"
            placeholder="请输入名称"
            clearable
            size="small"
            @keyup.enter.native="handleBusinessQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleBusinessQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="businessLoading" ref="bussinessTable" :data="businessList" :max-height="tableHeight2" @selection-change="handleBusinessSelectionChange" :reserve-selection="false">
        <el-table-column type="selection" width="55" align="center" prop="id" />
        <el-table-column label="企业名称" align="left" prop="companyName" width="320px"/>
        <el-table-column label="法人" align="center" prop="legalPerson" />
        <el-table-column label="联系电话" align="center" prop="telephone" />
      </el-table>

      <pagination
        v-show="totalBusiness>0"
        :total="totalBusiness"
        :page.sync="queryBusinessParams.pageNum"
        :limit.sync="queryBusinessParams.pageSize"
        @pagination="selectBusinessList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sbumitBusiness">确 定</el-button>
        <el-button @click="openBusiness=false">取 消</el-button>
      </div>
    </el-dialog>

    <!--    详情-->
    <el-dialog :title="title" :visible.sync="openView" width="700px">
      <el-form ref="form" :model="form" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="位置:" prop="position">{{form.position}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属经营户(或场所):" prop="companyName">{{form.companyName}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="灭火器数量:" prop="fireExtinguisherNumber">{{form.fireExtinguisherNumber}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消防箱数量:" prop="fireBoxNumber">{{form.fireBoxNumber}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="消防箱尺寸:" prop="fireBoxSize">{{form.fireBoxSize}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="玻璃尺寸:" prop="glassSize">{{form.glassSize}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="水带数量:" prop="waterBeltNumber">{{form.waterBeltNumber}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="枪头数量:" prop="gunHeadNumber">{{form.gunHeadNumber}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">{{form.remark}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片:" class="img" prop="imgList" v-if="form.imgList && form.imgList.length > 0 ">
              <ul>
                <li v-for="img in form.imgList" style="text-align: center;">
                  <el-image :preview-src-list="srcList" :src="img.url" style="width: 100px;height:100px;"></el-image>
                </li>
              </ul>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 消防设备导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的消防设备数据
          <el-link type="info" style="color:blue;" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment, exportEquipment, importTemplate } from "@/api/ledger/equipment";
import { listAccount } from "@/api/ledger/account";
import { getToken } from "@/utils/auth";
export default {
  name: "Equipment",
  data() {
    return {
      // 遮罩层
      loading: true,
      businessLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      totalBusiness: 0,
      // 消防设备表格数据
      equipmentList: [],
      srcList: [],
      businessList: [],
      dictList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      station_btn: false,
      openBusiness: false,
      openView: false,
      check_show: true,
      div_show: "none",
      check_height: "100%",
      check_content: "请输入场所",
      tableHeight: window.innerHeight - 275,
      tableHeight2: window.innerHeight - 450,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessId: undefined,
        stationId: undefined,
        stationName: undefined,
        position: undefined,
        companyName: undefined,
      },
      queryBusinessParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: undefined,
      },
      // 上传图片参数
      uploadImg: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        //  文件个数
        limit: 5
      },
      checkbox:{
        one:0,
        two:0
      },
      // 消防设备导入参数
      upload: {
        // 是否显示弹出层（消防设备导入）
        open: false,
        // 弹出层标题（消防设备导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ledger/equipment/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        position: [
          { required: true, message: "位置不能为空", trigger: "blur" }
        ],
        checkType: [
          { required: true, message: "请选择类型", trigger: "blur" }
        ],
      },
      dialogImageUrl: '',
      dialogVisible: false
    };
  },
  created() {
    const stationId = this.$route.params && this.$route.params.stationId;
    this.queryParams.stationId=stationId;
    const stationName = this.$route.params && this.$route.params.stationName;
    this.queryParams.stationName=stationName;
    const companyName = this.$route.params && this.$route.params.companyName;
    this.queryParams.companyName=companyName;
    const businessId = this.$route.params && this.$route.params.businessId;
    this.businessId=businessId;
    this.getList();
    this.dictList = [{"dictValue":"1","dictLabel":"经营户"},{"dictValue":"0","dictLabel":"一般场所"}];

    const roles = this.$store.getters && this.$store.getters.roles;
    for (let rol of roles){
      if ('station'==rol || 'hs_station'==rol){
        this.station_btn=true;
      }
    }
  },
  methods: {
    /** 查询消防设备列表 */
    getList() {
      this.loading = true;
      listEquipment(this.queryParams).then(response => {
        this.equipmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        businessId: undefined,
        stationId: undefined,
        position: undefined,
        companyName: undefined,
        fireExtinguisherNumber: undefined,
        fireBoxNumber: undefined,
        fireBoxSize: undefined,
        glassSize: undefined,
        waterBeltNumber: undefined,
        gunHeadNumber: undefined,
        delFlag: undefined,
        createTime: undefined,
        createId: undefined,
        updateTime: undefined,
        updateId: undefined,
        remark: undefined,
        checkType: undefined,
        imgList: [],
        imgs:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleBusinessQuery(){
      this.queryBusinessParams.pageNum = 1;
      this.selectBusinessList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if(this.businessId != undefined){
        this.form.companyName = this.queryParams.companyName;
        this.form.businessId = this.businessId;
      }
      this.form.checkType = '1';
      this.checkType(this.form.checkType)
      this.open = true;
      this.title = "添加消防设备";
    },
    /** 详情 **/
    handleView(row) {
      getEquipment(row.id).then(response => {
        this.form = response.data;
        const imgs = [];
        this.form.imgList.map(function (item) {
          imgs.push(item.url);
        });
        this.srcList = imgs;
        this.openView = true;
        this.title = "消防设备详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEquipment(id).then(response => {
        this.form = response.data;
        if (this.form.businessId != undefined){
          this.form.checkType = '1';
          this.checkType(this.form.checkType);
        }else {
          this.form.checkType = '0';
          this.checkType(this.form.checkType);
        }
        const imgs = [];
        this.form.imgList.map(function (item) {
          imgs.push(item.url);
        });
        this.form.imgs = imgs;
        this.open = true;
        this.title = "修改消防设备";
      });
    },
    handleBusinessSelectionChange(selection) {
      if(selection.length > 1){
        this.$refs.bussinessTable.clearSelection();
        this.$refs.bussinessTable.toggleRowSelection(selection.pop());
      }else{
        this.selectBusiness = selection.pop();
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateEquipment(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addEquipment(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该消防设备的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delEquipment(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有消防设备数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportEquipment(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "消防设备导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    beforeImageUpload(file){
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
    },
    exceedFile(files, fileList) {
      let msg = `最多只能上传${this.uploadImg.limit}个图片`;
      this.$message.warning(msg)
    },
    //图片上传
    handleRemove(file, fileList) {
      this.form.imgs.splice(this.form.imgs.indexOf(file.url),1);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureSuccess(response, file) {
      this.form.imgs.push(response.fileName);
    },
    selectBussiness(){
      this.resetForm("queryBusinessForm");
      this.selectBusinessList();
      this.openBusiness = true;
    },
    selectBusinessList() {
      this.businessLoading = true;
      listAccount(this.queryBusinessParams).then(response => {
        this.businessList = response.rows;
        this.totalBusiness = response.total;
        this.businessLoading = false;
      });
    },
    sbumitBusiness(){
      if(this.selectBusiness == undefined){
        this.msgError("请选择经营户");
      }else{
        this.openBusiness = false;
        this.form.companyName = this.selectBusiness.companyName;
        this.form.businessId = this.selectBusiness.id;
      }
    },
    checkType(val){
      if (val && val === '1'){
        this.check_show = true;
        this.div_show = "block";
        this.check_height = "85%"
        this.check_content = "请选择经营户"
      }else if (val && val === '0'){
        this.check_show = false;
        this.div_show = "none"
        this.check_height = "100%"
        this.check_content = "请输入场所"
      }
    }
  }
};
</script>
<style>
  .people-to {
    width: 100%;
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
  }
  .to-search{
    width:40px;
    height: 36px;
    line-height:36px;
    text-align:center;
    background: #1890ff;
    color: #fff;
  }
  .img ul{
    padding: 0;
  }
  .img ul li{
    float:left;
    width:20%;
    list-style:none;
    width: 100px;
    margin-right: 2%;
  }
  #queryBusinessForm td{
    height: 30px !important;
  }
  .el-upload__tip{
    font-size: 14px;
  }
</style>
